<template>
  <div class="departments-container">
    <el-card class="box-card">
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织结构" name="first">
          <el-row type="flex" justify="space-between">
            <el-col :span="8">
              深圳传智播客教育科技股份有限公司
            </el-col>
            <el-col class="right-col" :span="4">
              <span class="leader">负责人</span>
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item><el-button
                    type="text"
                    @click="addDep('')"
                  >添加子部门</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <el-divider />
          <el-tree v-loading="loading" :data="departs">
            <el-row slot-scope="{ data }" type="flex" justify="space-between">
              <el-col :span="8">
                {{ data.name }}
              </el-col>
              <el-col class="right-col" :span="4">
                <span class="leader">{{ data.manager }}</span>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item><el-button
                      type="text"
                      @click="addDep(data.id)"
                    >添加子部门</el-button></el-dropdown-item>
                    <el-dropdown-item><el-button
                      type="text"
                      @click="editDep(data.id)"
                    >编辑部门</el-button></el-dropdown-item>
                    <el-dropdown-item><el-button
                      type="text"
                      @click="delDep(data.id)"
                    >删除部门</el-button></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :show-close="false"
    >
      <el-form ref="depForm" :model="form" :rules="rules" @closed="clearAll">
        <el-form-item
          prop="name"
          label="部门名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="code"
          label="部门编码"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="manager"
          label="部门负责人"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.manager"
            placeholder="请选择"
            @focus="getManagers"
          >
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="introduce"
          label="部门介绍"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartmentById,
  editDepartments,
  delDepartmentById
} from '../../api/departments'
import { getEmployeeSimple } from '../../api/employees'
export default {
  name: 'Departments',
  data() {
    return {
      loading: false,
      dialogFormVisible: false,
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      formLabelWidth: '120px',
      activeName: 'first',
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ],
      managerList: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度为1-50个字符', trigger: 'blur' },
          {
            // async validator(rule, value, callback) {
            validator: async(rule, value, callback) => {
              const res = await getDepartments()
              const ruleRes = res.depts.filter(v => {
                if (this.form.id) {
                  // 修改
                  if (value === v.name && this.form.id !== v.id) {
                    return true
                  }
                } else {
                  // 新增
                  if (value === v.name) {
                    return true
                  }
                }
              })
              ruleRes.length === 0
                ? callback()
                : callback(new Error('部门名称重复'))
              // ? callback(new Error('部门名称重复'))
              // : callback()
              // const res = await getDepartments()
              // console.log(res)
              // const filterRes = res.depts.filter(v => {
              //   if (value === v.name) {
              //     return true
              //   } else {
              //     return false
              //   }
              // })
              // if (filterRes.length === 0) {
              //   callback()
              // } else {
              //   callback(new Error('有重复的部门，请重新输入'))
              // }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度为1-50个字符', trigger: 'blur' },
          {
            // async validator(rule, value, callback) {
            //   const res = await getDepartments()
            //   // console.log(res)
            //   const filterRes = res.depts.filter(v => {
            //     if (value === v.code) {
            //       return true
            //     } else {
            //       return false
            //     }
            //   })
            //   if (filterRes.length === 0) {
            //     callback()
            //   } else {
            //     callback(new Error('有重复的部门，请重新输入'))
            //   }
            // },
            validator: async(rule, value, callback) => {
              const res = await getDepartments()
              const ruleRes = res.depts.filter(v => {
                if (this.form.id) {
                  // 修改
                  if (value === v.code && this.form.id !== v.id) {
                    return true
                  }
                } else {
                  // 新增
                  if (value === v.code) {
                    return true
                  }
                }
              })
              ruleRes.length === 0
                ? callback()
                : callback(new Error('部门名称重复'))
            },
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门名称不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '长度为1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 点击空白
    clearAll() {
      this.$refs.depForm.resetFields()
      this.form = {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      }
      this.$nextTick(() => {
        this.$refs.depForm.clearValidate()
      })
    },
    // 新增部门
    addDep(pid) {
      this.form.pid = pid
      this.dialogFormVisible = true
    },
    // 删除部门
    delDep(id) {
      this.$confirm('是否删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delDepartmentById(id)
          this.$message.success('删除成功')
          this.getData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 修改部门
    async editDep(id) {
      this.dialogFormVisible = true
      const res = await getDepartmentById(id)
      // console.log(editRes)
      this.form = res
    },
    // 取消
    cancel() {
      this.dialogFormVisible = false
      this.$refs.depForm.resetFields()
      this.form = {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      }
    },
    // 获取部门信息
    async getData() {
      this.loading = true
      const res = await getDepartments()
      // console.log(res)
      function formatData(list, pid) {
        return list.filter(v => {
          if (v.pid === pid) {
            v.children = formatData(list, v.id)
            return true
          } else {
            return false
          }
        })
      }
      const dataRes = formatData(res.depts, '')
      this.departs = dataRes
      setTimeout(() => {
        this.loading = false
      }, 300)
    },

    async getManagers() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.managerList = res
    },
    // 确认
    submitForm() {
      this.$refs.depForm.validate(async valid => {
        if (valid) {
          // 修改部门逻辑
          if (this.form.id) {
            await editDepartments(this.form)
            this.$message.success('修改成功')
          } else {
            // 新增部门逻辑
            await addDepartments(this.form)
            this.$message.success('新增成功')
          }

          this.dialogFormVisible = false
          this.getData()
          this.$refs.depForm.resetFields()
          this.form = {
            code: '',
            introduce: '',
            manager: '',
            name: ''
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.departments-container {
  padding: 20px;
  background-color: #f0f2f5;
  font-size: 14px;
  .right-col {
    text-align: right;
  }
  .leader {
    margin-right: 10px;
  }
  .el-row {
    width: 100%;
  }
  .el-tabs__content {
    padding: 20px 90px;
    .el-divider {
      margin-top: 10px;
    }
  }
}
</style>
